import axios from 'axios'
import store from '@/store'
import router from '@/router'
import to from 'await-to-js'
import { refreshTokenAPI } from '@/api/user'
const instance = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 5000
})
// 导出一个新axios实例调用接口的函数，返回值promise
const example = ({ url, method = 'get', params, data, headers }) => {
  const promise = instance({ url, method, params, data, headers })
  return to(promise)
}
export default example

// 请求拦截器
instance.interceptors.request.use(config => {
  const token = store.state.user.token
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
}, err => Promise.reject(err))

// 响应拦截器
instance.interceptors.response.use(res => res, async err => {
  if (err.response && err.response.status === 401) {
    const [err2, res] = await to(refreshTokenAPI(store.state.user.refreshToken))
    if (err2) {
      store.commit('user/setToken', '')
      router.push('/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath))
    } else {
      store.commit('user/setToken', res.data.data.token)
      return instance(err.config)
    }
  }
  return Promise.reject(err)
})
